<template>
  <n-scrollbar x-scrollable style="max-height: 100vh">
    <CommonPage show-footer>
      <div>
        <n-form ref="form"
                :model="searchCondition"
                :show-require-mark="false"
                label-align="right"
                label-placement="left"
                label-width="80px">
          <div>
           <div class="grid md:flex md:flex-wrap md:gap-x-1">
            <n-form-item>
              <label>仓库名：</label>
             <n-select
                 clearable
                 filterable
                 v-model:value="searchCondition.storeId"
                 placeholder="请选择仓库"
                 :options="stores">
             </n-select>
              </n-form-item>
              <n-form-item style="margin-left: 10px">
                <label>供应商：</label>
                <n-select
                    clearable
                    filterable
                    v-model:value="searchCondition.supplierId"
                    :options="suppliers"
                    placeholder="请选择">
                </n-select>
              </n-form-item>

            <n-form-item style="margin-left: 10px">
              <label>采购时间：</label>
              <n-date-picker v-model:value="timeRange" type="daterange" clearable/>
            </n-form-item>
            <n-form-item style="margin-left: 10px">
              <label style="width: 70px">产品名称：</label>
                <n-input
                    v-model:value="searchCondition.productName"
                    placeholder="输入产品名称"
                    clearable
                    style="width: 180px"
                >
                </n-input>
            </n-form-item>
            <n-form-item style="margin-left: 10px" >
              <n-button type="primary" @click="searchByCondition">
                筛选
              </n-button>
            </n-form-item>
            <n-form-item>
              <n-button
                  style="margin-left: 15px"
                  type="primary"
                  @click="showForm=true"
              >
                创建采购单
              </n-button>
            </n-form-item>
            <n-form-item>
              <n-button style="margin-left: 15px" type="error" @click="deletePurchaseOrders">
                批量删除
              </n-button>
            </n-form-item>
             <n-form-item style="margin-left: 10px">
               <n-button @click="exportListInfo"
                         type="primary">
                 导出
               </n-button>
             </n-form-item>
          </div>
          </div>
        </n-form>
        <AddDocumentForm
            :products="products"
            :stores="filteredStores"
            :suppliers="filteredSuppliers"
            :contactPersons="contactPersons"
            :option="option"
            @update-page="searchByCondition"
            :show="showForm"
            :onClose="handleClose" />
        <UpdateDocumentForm
            :products="products"
            :stores="filteredStores"
            :suppliers="filteredSuppliers"
            :contactPersons="contactPersons"
            :option="option"
            @update-page="searchByCondition"
            :show1="showForm1"
            :onClose="handleClose"
            :attribute="currentAttribute"
        />
        <AuditingDocument
            :products="products"
            :stores="filteredStores"
            :suppliers="filteredSuppliers"
            :contactPersons="contactPersons"
            :option="option"
            @update-page="searchByCondition"
            :show1="showForm2"
            :onClose="handleClose"
            :attribute="currentAttribute"
        />
      <n-data-table
          remote
          :single-line="false"
          ref="table"
          :columns="columns"
          :data="purchaseDocumentList"
          :loading="loading"
          :pagination="paginationReactive"
          :row-key="rowKey"
          :scroll-x="900"
          @update:checked-row-keys="handleCheck"
      />
      </div>
    </CommonPage>
  </n-scrollbar>
</template>

<script setup>
import {h, onMounted, reactive, ref} from 'vue'
import api from '@/api/admin';
import {useUserStore} from '@/store';
import {useRouter} from 'vue-router';
import {formatDate, formatDateTime} from "@/utils";
import {NCascader, NTag} from 'naive-ui'
import PurchaseActions from "@/views/admin/category/components/category-actions.vue";
import AddDocumentForm from './components/document-add.vue'
import UpdateDocumentForm from './components/document-edit.vue'
import AuditingDocument from './components/document-auditing.vue'

const userStore = useUserStore()
const router = useRouter()
const showForm=ref(false)
const showForm1=ref(false)
const showForm2=ref(false)
const products=ref([])
const contactPersons=ref([])
const handleClose = () => {
  showForm.value=false;
  showForm1.value=false;
  showForm2.value=false;
};
const stores = ref([])
stores.value.push({
  label:'全部',
  value:-1,
})
const queryStoreList = async () => {
  loading.value = true
  try {
    const res = await api.findAllStore()
    if(res.code === 200) {
      res.data.map((item)=>{
        stores.value.push({
          label: item.name,
          value: item.id
        })
      })
    }
    else {
      $message.error(res.message)
    }
  } catch (err) {
    $message.error("获取仓库信息失败！")
  }finally{
    loading.value = false
  }
}
const suppliers=ref([])
suppliers.value.push({
  label:'全部',
  value:-1,
})
function handleChange(value) {
  console.log(value)
}
const timeRange = ref(null)
const loading = ref(true)
const logList = ref([])
const checkedRowKeysRef = ref([]);
const handleCheck = (rowKeys) => {
  checkedRowKeysRef.value = rowKeys;
}
const currentAttribute = ref(null); // 当前编辑的属性
const columns = [
  {
    type: 'selection',
    fixed: 'left',
  },
  {
    key: 'colId',
    title: '序号',
    width: 60,
  },
  {
    key: 'productName',
    title: '产品名称',
    width: 200,

  },
  {
    key: 'quantity',
    title: '采购数量',
    width: 65,

  },
  {
    key: 'price',
    title: '花费金额',
    width: 65,

  },
  {
    key: 'storeName',
    title: '仓库名称',
    width: 100,

  },
  {
    key: 'supplierName',
    title: '供应商',
    width: 100,

  },
  {
    key: 'adminName',
    title: '联系人',
    width: 100,

  },
  {
    key: 'contactPhone',
    title: '联系电话',
    width: 100,

  },
  {
    key: 'status',
    title: '状态',
    width: 100,
    render(row) {
      if (row.status === "待采购") {
        return h(
            NTag,
            {
              type: 'info',
              bordered: false,
              style: {cursor: 'pointer'},
              onClick: () => handleStatusClick(row)
            },
            {
              default: () => '待采购'
            }
        );
      } else if (row.status === "已取消") {
        return h(
            NTag,
            {
              type: 'error',
              bordered: false
            },
            {
              default: () => '已取消'
            }
        );
      } else if (row.status === "采购中") {
        return h(
            NTag,
            {
              type: 'info',
              bordered: false,
              style: {cursor: 'pointer'},
              onClick: () => handleStatusClick(row)
            },
            {
              default: () => '采购中'
            }
        );
      }else if (row.status === "已完成") {
        return h(
            NTag,
            {
              type: 'success',
              bordered: false,
              style: {cursor: 'pointer'},
            },
            {
              default: () => '已完成'
            }
        );
      }
    }
  },
  {
    key: 'createTime',
    title: '创建时间',
    width: 100,

  },
  {
    key: 'updateTime',
    title: '更新时间',
    width: 100,

  },
  {
    key: 'operation',
    title: '操作',
    width: 125,
    render(row) {
      if (row.status !== "已完成" && row.status !== "已取消") {
        return h(
            PurchaseActions,
            {
              onClickDelete: () => onDeletePurchaseDocument(row),
              onClickEdit: () => onEditPurchaseDocument(row),
            }
        );
      }
    }
  },
]
const handleStatusClick = async (purchaseOrder) => {
  currentAttribute.value = purchaseOrder; // 设置当前编辑的属性
  showForm2.value = true; // 显示编辑窗口
}
// 定义搜索类型和搜索查询的值
const searchType = ref(null)
const searchQuery = ref('')
const searchCondition = ref({
	supplierId: -1,
	storeId: -1,
	productName: '',
	timeFrom: '',
	timeTo: ''
});
// 定义搜索类型的选项
const searchOptions = [
  {label: '产品名', value: 'name'},
  {label: '联系人', value: 'adminName'},
  {label: '供应商', value: 'supplier'},
  {label: '仓库', value: 'store'}
]

// 定义输入框的占位符
const inputPlaceholder = ref('')

// 更新输入框的占位符
function updatePlaceholder(value) {
  const selectedOption = searchOptions.find(option => option.value === value)
  inputPlaceholder.value = selectedOption ? `请输入${selectedOption.label}` : '请输入内容'
}

// 定义搜索处理函数
function handleSearch() {
  console.log(`搜索类型: ${searchType.value}, 搜索内容: ${searchQuery.value}`)
}

// 定义搜索图标点击处理函数
function handleSearchIconClick() {
  console.log('Search icon clicked')
  handleSearch()
}

// 设置默认选项和占位符
onMounted(() => {
  if (searchOptions.length > 0) {
    searchType.value = searchOptions[0].value
    updatePlaceholder(searchType.value)
  }
})


let total = 0
const paginationReactive = reactive({
  page: 1,
  pageSize: 50,
  showSizePicker: true,
  pageSizes: [50, 100, 150],
  itemCount: 0,
  prefix: () => {
    return '查询出 ' + total + '条记录';
  },
  onChange: (page) => {
    paginationReactive.page = page;
    queryByPage()
  },
  onUpdatePageSize: (pageSize) => {
    paginationReactive.pageSize = pageSize;
    paginationReactive.page = 1;
    queryByPage()
  }
});

const deletePurchaseOrders = () => {
  if (checkedRowKeysRef.value.length <= 0) {
    $message.error("当前并未选择采购单！")
    return
  }
  $dialog.confirm({
    title: '警告',
    content: '您确定删除当前所选采购单？',
    positiveText: '确定',
    negativeText: '取消',
    onPositiveClick: async () => {
      const ids = checkedRowKeysRef.value.join(",")
      console.log(ids)
      loading.value = true
      try {
        const res = await api.deletePurchaseOrders({params:{ids}})
        if (res.code === 200) {
          $message.success("删除所选采购单成功！")
          // await queryByPage()
          await searchByCondition()
        } else {
          $message.error(res.message)
        }
      } catch (err) {
        $message.error("删除所选采购单失败！")
      } finally {
        loading.value = false
      }
    },
  })
}

const searchByCondition = async () => {
	if (timeRange.value !== null) {
		searchCondition.value.timeFrom = formatDate(timeRange.value[0])
		searchCondition.value.timeTo = formatDate(timeRange.value[1])
	}
	loading.value = true
	try {
		paginationReactive.page = 1;
		const res = await api.findPagePurchaseOrder({
      params: {
	      ...searchCondition.value,
	      pageNum: paginationReactive.page,
	      pageSize: paginationReactive.pageSize,
      }
		})
		if (res.code === 200) {
			total = res.data.total
			paginationReactive.itemCount = total
			purchaseDocumentList.value = res.data.records.map((item, i) => {
				return {
					...item,
					colId: i + 1 + (paginationReactive.page - 1) * paginationReactive.pageSize
				}
			})
		} else {
			$message.error(res.message)
		}
	} catch (err) {
		$message.error("查询采购单失败！")
	} finally {
		loading.value = false
	}
}
const onDeletePurchaseDocument = async (log) => {
  $dialog.confirm({
    title: '警告',
    content: '您确定删除当前采购单？',
    positiveText: '确定',
    negativeText: '取消',
    onPositiveClick: async () => {
      const {id} = log
      loading.value = true
      try {
        const res = await api.deletePurchaseOrder({id})
        if (res.code === 200) {
          $message.success("删除采购单成功！")
          // await queryByPage()
          await searchByCondition()
        } else {
          $message.error(res.message)
        }
      } catch (err) {
        $message.error("删除采购单失败！")
      } finally {
        loading.value = false
      }
    }
  })
}

const onEditPurchaseDocument = async (purchaseDocument) => {
  currentAttribute.value = purchaseDocument; // 设置当前编辑的属性
  showForm1.value = true; // 显示编辑窗口
}
const purchaseDocumentList=ref()
const queryByPage = async () => {
  loading.value = true
  try {
    const res = await api.findPagePurchaseOrder(
        {
          params: {
	          pageNum: paginationReactive.page,
	          pageSize: paginationReactive.pageSize,
          }
        })
    if (res.code === 200) {
	    total = res.data.total
	    paginationReactive.itemCount = total
	    const baseCount = (paginationReactive.page - 1)*paginationReactive.pageSize
	    purchaseDocumentList.value = res.data.records.map((item,i)=>{
		    return {...item,
			    colId: baseCount + i + 1,
		    }
	    })
      $message.success("获取采购单成功！")
    } else {
      $message.error(res.message)
    }
  } catch (err) {
    $message.error("获取采购单失败！")
  } finally {
    loading.value = false
  }
}
const querySupplierList = async () => {
  loading.value = true
  try {
    const res = await api.findAllSupplier()
    if(res.code === 200) {
      res.data.map((item)=>{
        suppliers.value.push({
          label: item.name,
          value: item.id
        })
      })
    }
    else {
      $message.error(res.message)
    }
  } catch (err) {
    $message.error("获取供应商信息失败！")
  }finally{
    loading.value = false
  }
}
const queryProductList = async () => {
  loading.value = true
  try {
    const res = await api.findAllProduct()
    if(res.code === 200) {
      res.data.map((item)=>{
        products.value.push({
          label: item.name,
          value: item.id
        })
      })
    }
    else {
      $message.error(res.message)
    }
  } catch (err) {
    $message.error("获取产品信息失败！")
  }finally{
    loading.value = false
  }
}
const queryContactPersonList = async () => {
  loading.value = true
  try {
    const res = await api.findAdminByRole({
      role: 'PURCHASEADMIN'
    })
    if(res.code === 200) {
      res.data.map((item)=>{
        contactPersons.value.push({
          label: item.name,
          value: item.id,
        })
      })
    }
    else {
      $message.error(res.message)
    }
  } catch (err) {
    $message.error("获联系人信息失败！")
  }finally{
    loading.value = false
  }
}
// 过滤掉 '全部' 选项
const filteredStores = computed(() => stores.value.filter(store => store.value !== -1));
const filteredSuppliers = computed(() => suppliers.value.filter(supplier => supplier.value !== -1));

const exportListInfo = async () => {
  const res = await api.exportPurchaseDocumentList({
    supplierId: searchCondition.value.supplierId,
    storeId: searchCondition.value.storeId,
    productName: searchCondition.value.productName,
    timeFrom: searchCondition.value.timeFrom,
    timeTo: searchCondition.value.timeTo,
  });
  const contentDisposition = res.headers["content-disposition"]
  let original_fileName = ""
  if(contentDisposition) {
    const uri = res.headers["content-disposition"].split("=")[1]
    original_fileName = window.decodeURI(uri)
  }
  const blob = new Blob([res.data], {type: "application/vnd.ms-excel"});
  if(window.navigator && window.navigator.msSaveOrOpenBlob) {
    window.navigator.msSaveOrOpenBlob(blob, original_fileName);
  } else{
    const fileName = original_fileName;
    const elink = document.createElement('a')
    document.body.appendChild(elink)
    elink.download= fileName;
    elink.style.display ="none"
    elink.href  = window.URL.createObjectURL(blob)
    elink.click()
    window.URL.revokeObjectURL(elink.href)
    document.body.removeChild(elink)
  }
}
const rowKey = (rowData) => {
  return rowData.id
}
onMounted(() => {
  queryByPage()
  queryStoreList()
  querySupplierList()
  queryProductList()
  queryContactPersonList()
})
</script>
<style scoped>
:deep(.n-data-table-th__title),
:deep(.n-data-table-td) {
  text-align: center;

}

:deep(.n-select) {
  width: 140px !important;
}

:deep(.two-line-description) {
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 2; /* 控制显示的行数 */
  overflow: hidden;
}

.search-container {
  display: flex;
  align-items: center;
  border: 1px solid rgba(217, 217, 217, 0.33);
  border-radius: 6px;
  overflow: hidden;
  margin-left: 15px;
  margin-top: -77px;
}

.search-container .n-select {
  width: 100px;
  border-right: 1px solid rgba(217, 217, 217, 0.33);
}

.search-container .n-input {
  flex-grow: 1;
}

.search-icon {
  width: 20px;
  height: 20px;
  cursor: pointer;
}
</style>
